from django.shortcuts import render
from rest_framework import status
from rest_framework.views import APIView
from libs.captcha.captcha import captcha
from django_redis import get_redis_connection
from django.http import HttpResponse
from rest_framework.generics import GenericAPIView
import random
from rest_framework.response import Response
from libs.yuntongxun.sms import CCP
from .serializers import RegisterSMSCodeSerializer
from rest_framework.permissions import IsAuthenticated
"""
图片验证码
使用的是captcha
"""
class RegisterImageCodeView(APIView):
    def get(self,request,image_code_id):
        #1,生成图片验证码
        text,image_data = captcha.generate_captcha()

        #2,保存验证码值到redis
        redis_conn = get_redis_connection("code")
        #参数1: 存储在redis的key值,  参数二:有效期  参数三:具体的内容
        redis_conn.setex("img_%s"%image_code_id,5*60,text)

        #3,返回图片
        return HttpResponse(image_data,content_type="image/png")


"""
发送短信验证码
1, 前端携带,手机号,图片验证码,图片验证码编号
2, 校验数据,发送短信
3, 返回响应
"""
class RegisterSMSCodeView(GenericAPIView):

    serializer_class = RegisterSMSCodeSerializer

    def get(self,request,mobile):
        #1,获取参数
        dict_data = request.query_params

        #2,校验参数(创建序列化器对象,校验)
        serializer = self.get_serializer(data=dict_data)
        serializer.is_valid(raise_exception=True)

        #3,判断,是否过了一分钟
        redis_conn = get_redis_connection("code")
        send_flag = redis_conn.get("send_flag_%s"%mobile)

        if send_flag:
            if send_flag.decode() == "1":
                return Response({"message":"短信发送频繁"},status=status.HTTP_429_TOO_MANY_REQUESTS)

        #3,生成短信验证码
        sms_code = "%06d"%random.randint(0,999999)
        print("sms_code=%s"%sms_code)

        #4,保存到redis中
        redis_conn.setex("sms_%s"%mobile,5*60,sms_code)
        #参数1:key    参数:time     参数:value
        redis_conn.setex("send_flag_%s" % mobile,60,1) #存储标记,不让用户一分钟内多次发送

        #5,发送短信验证码
        # CCP().send_template_sms(mobile, [sms_code, 5], 1)
        from celery_tasks.sms.tasks import send_sms
        send_sms.delay(mobile,sms_code)

        #6,返回响应
        return Response({"message":"OK"})

